package com.ruoyi.phoneController;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.domain.MobilEvaluate;
import com.ruoyi.mapper.MobilEvaluateMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 手机端评价Controller
 *
 * @author ruoyi
 * @date 2025-01-20
 */
@RestController
@RequestMapping("/mobile/evaluate")
public class MobilEvaluateController extends BaseController {
    @Autowired
    private MobilEvaluateMapper mobilEvaluateMapper;


    /**
     * 根据商户ID查询评价列表
     */
    @GetMapping("/merchant/{merchantId}")
    public AjaxResult getEvaluatesByMerchant(@PathVariable Integer merchantId) {
        List<MobilEvaluate> evaluates = mobilEvaluateMapper.selectEvaluatesByMerchantId(merchantId);
        return success(evaluates);
    }

    /**
     * 根据用户ID查询评价列表
     */
    @GetMapping("/user/{userId}")
    public AjaxResult getEvaluatesByUser(@PathVariable Integer userId) {
        List<MobilEvaluate> evaluates = mobilEvaluateMapper.selectEvaluatesByUserId(userId);
        return success(evaluates);
    }

    /**
     * 根据ID查询评价详情
     */
    @GetMapping("/{id}")
    public AjaxResult getEvaluateDetail(@PathVariable Integer id) {
        MobilEvaluate evaluate = mobilEvaluateMapper.selectMobilEvaluateById(id);
        if (evaluate == null) {
            return error("评价不存在");
        }
        return success(evaluate);
    }

    /**
     * 提交评价
     */
    @PostMapping
    public AjaxResult addEvaluate(@RequestBody MobilEvaluate mobilEvaluate) {
        try {
            // 验证必填字段
            if (mobilEvaluate.getUserId() == null) {
                return error("用户ID不能为空");
            }
            if (mobilEvaluate.getMerchantId() == null) {
                return error("商户ID不能为空");
            }
            if (mobilEvaluate.getOrderId() == null || mobilEvaluate.getOrderId().trim().isEmpty()) {
                return error("订单ID不能为空");
            }
            if (mobilEvaluate.getRate() == null || mobilEvaluate.getRate() < 1 || mobilEvaluate.getRate() > 5) {
                return error("评分必须在1-5之间");
            }
            
            // 设置默认值
            if (mobilEvaluate.getTime() == null) {
                mobilEvaluate.setTime(new Date());
            }
            if (mobilEvaluate.getDeleted() == null) {
                mobilEvaluate.setDeleted(0);
            }
            
            int result = mobilEvaluateMapper.insertMobilEvaluate(mobilEvaluate);
            if (result > 0) {
                return success("评价提交成功");
            } else {
                return error("评价提交失败");
            }
        } catch (Exception e) {
            logger.error("提交评价失败", e);
            return error("评价提交失败：" + e.getMessage());
        }
    }

    /**
     * 修改评价
     */
    @PutMapping
    public AjaxResult updateEvaluate(@RequestBody MobilEvaluate mobilEvaluate) {
        try {
            if (mobilEvaluate.getId() == null) {
                return error("评价ID不能为空");
            }
            
            int result = mobilEvaluateMapper.updateMobilEvaluate(mobilEvaluate);
            if (result > 0) {
                return success("评价修改成功");
            } else {
                return error("评价修改失败");
            }
        } catch (Exception e) {
            logger.error("修改评价失败", e);
            return error("评价修改失败：" + e.getMessage());
        }
    }

    /**
     * 删除评价
     */
    @DeleteMapping("/{id}")
    public AjaxResult deleteEvaluate(@PathVariable Integer id) {
        try {
            int result = mobilEvaluateMapper.deleteMobilEvaluateById(id);
            if (result > 0) {
                return success("评价删除成功");
            } else {
                return error("评价删除失败");
            }
        } catch (Exception e) {
            logger.error("删除评价失败", e);
            return error("评价删除失败：" + e.getMessage());
        }
    }

    /**
     * 查询评价统计信息
     */
    @GetMapping("/statistics/merchant/{merchantId}")
    public AjaxResult getEvaluateStatistics(@PathVariable Integer merchantId) {
        // 查询该商户的所有评价
        List<MobilEvaluate> evaluates = mobilEvaluateMapper.selectEvaluatesByMerchantId(merchantId);
        
        if (evaluates.isEmpty()) {
            return success()
                    .put("totalCount", 0)
                    .put("averageRate", 0.0)
                    .put("rateDistribution", new int[]{0, 0, 0, 0, 0});
        }
        
        // 计算统计信息
        int totalCount = evaluates.size();
        double totalRate = evaluates.stream().mapToInt(MobilEvaluate::getRate).sum();
        double averageRate = totalRate / totalCount;
        
        // 计算各星级分布
        int[] rateDistribution = new int[5]; // 1-5星的数量
        for (MobilEvaluate evaluate : evaluates) {
            if (evaluate.getRate() >= 1 && evaluate.getRate() <= 5) {
                rateDistribution[evaluate.getRate() - 1]++;
            }
        }
        
        return success()
                .put("totalCount", totalCount)
                .put("averageRate", Math.round(averageRate * 10.0) / 10.0) // 保留1位小数
                .put("rateDistribution", rateDistribution);
    }

    /**
     * 检查是否可以评价
     */
    @GetMapping("/check-permission")
    public AjaxResult checkEvaluatePermission(
            @RequestParam Integer userId,
            @RequestParam Integer merchantId,
            @RequestParam String orderId) {
        
        // 检查是否已经评价过
        MobilEvaluate query = new MobilEvaluate();
        query.setUserId(userId);
        query.setMerchantId(merchantId);
        query.setOrderId(orderId);
        query.setDeleted(0);
        
        List<MobilEvaluate> existingEvaluates = mobilEvaluateMapper.selectMobilEvaluateList(query);
        
        if (!existingEvaluates.isEmpty()) {
            return error("该订单已评价过");
        }
        
        return success("可以评价");
    }

}











